import React, { useEffect } from 'react';
import axios from 'axios'
import { useSelector, useDispatch } from 'react-redux'
import { Stepper, Checkbox, SubmitBar } from 'react-vant'
const App = () => {
  // 购物车列表数据
  const carList = useSelector(state => state.car.carList);
  // 全选状态 = 
  //   每一个人状态都为true       全选true
  //   存在任意一项状态都为false   全选false
  const allCheck = carList.every(v => v.check)
  // 总价
  const allPrice = carList.filter(v => v.check).reduce((p, n) => {
    return p + n.price * n.count
  }, 0)
  const dispath = useDispatch()
  const getCarList = async () => {
    const resp = await axios.get('/api/car/list')
    dispath({ type: 'initCarList', payload: resp.data.data })
    console.log(resp.data.data)
  }

  useEffect(() => {
    getCarList()
  }, [])

  return (
    <div>
      {
        carList.map((v, i) => {
          return (
            <dl key={i} style={{ display: 'flex' }}>
              <dd>
                <Checkbox checked={v.check}
                  onChange={() => dispath({ type: 'oneCheck', payload: v })}></Checkbox>
              </dd>
              <dt>
                <img src={v.image} alt="" />
              </dt>
              <dd>
                <h3>{v.title}</h3>
                <h4>{v.price}</h4>
                <Stepper
                  value={v.count}
                  onPlus={() => dispath({ type: 'addCount', payload: v })}
                  onMinus={() => dispath({ type: 'subCount', payload: v })}
                  min={1}
                  onOverlimit={() => dispath({ type: 'delCar', payload: v })}
                ></Stepper>
              </dd>
            </dl>
          )
        })
      }
      <div style={{ height: 50 }}>
        <SubmitBar
          price={allPrice * 100}
          buttonText="提交订单"
        >
          <Checkbox
            checked={allCheck}
            onChange={() => dispath({ type: 'allCheck', payload: !allCheck })}
          >全选</Checkbox>
        </SubmitBar>
      </div>
    </div>
  )
}

export default App